﻿
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace AdverseEventReportSystem.Utils {
	public static class Common {
		public const string AppKey = "appKey";
		public const string Sign = "sign";
		#region 执行线程异步回调方法，内部发生异常IIS不受影响
		/// <summary>
		/// 执行线程异步回调方法，内部发生异常IIS不受影响 
		/// </summary>
		/// <param name="call">异步回调方法</param>
		/// <param name="param">回调方法的传入参数</param>
		public static void RunAsyn(System.Threading.WaitCallback call, object param) {
			call.BeginInvoke(param, null, null);
		}
		#endregion
		#region 生成签名
		/// <summary>
		///  获取防篡改签名，组织原始字符串的方式为：先get后post，该方法要求appKey和sign必须通过QueryString方式传递 
		/// </summary>
        /// <param name="getDic">通过QueryString方式传递的键值集合,如果内部包含appKey或者sign，相关字段在组织原始字符串时将会被移除</param>
		/// <param name="appKey">appKey</param>
		/// <param name="token">token</param>
        /// <param name="postDic">通过Form方式传递的键值集合，如果包含appKey或者sign，此部分不会被做特殊处理</param>
		/// <returns></returns>        
        public static string GenerateCheckWord(Dictionary<string, string> getDic, string appKey, string token, out string waitEncrypt, Dictionary<string, string> postDic = null) {
			string checkWord = string.Empty;
            var dic = GetSortedDictionary(getDic,
			(k) => {//过滤appKey及sign  
				return string.Equals(k, Common.AppKey, StringComparison.OrdinalIgnoreCase)
					|| string.Equals(k, Common.Sign, StringComparison.OrdinalIgnoreCase);
			});
			StringBuilder sb = new StringBuilder();
			sb.Append(appKey);//在头部添加appkey
			FillStringBuilder(sb, dic);//将QueryString填入StringBuilder  
            dic = GetSortedDictionary(postDic);
			FillStringBuilder(sb, dic);//将Form填入StringBuilder  
			sb.Append(token);//在尾部添加appSecret
			waitEncrypt = sb.ToString();
			checkWord = StringHelper.Encrypt(sb.ToString());
			return checkWord;
		}
		#endregion
        #region 获取排序的键值对
        /// <summary>
		/// 获取排序的键值对  
		/// </summary>
		/// <param name="collection"></param>
		/// <param name="filter"></param>
		/// <returns></returns>
        private static SortedDictionary<string, string> GetSortedDictionary(Dictionary<string, string> dic, Func<string, bool> filter = null) {
			SortedDictionary<string, string> sortDic = new SortedDictionary<string, string>();
            if (dic != null && dic.Count > 0) {
                foreach (var k in dic.Keys) {
					if (filter == null || !filter(k)) {
						//如果没设置过滤条件或者无需过滤  
                        sortDic.Add(k, dic[k]);
					}
				}
			}
            return sortDic;
		}
        #endregion
        #region 按key顺序组织字符串
        /// <summary>
		/// 按key顺序组织字符串 
		/// </summary>
		/// <param name="builder"></param>
		/// <param name="dic"></param>
		private static void FillStringBuilder(StringBuilder builder, SortedDictionary<string, string> dic) {
			var index = 0;
			foreach (var kv in dic) {
				if (index > 0) {
					builder.Append('&');
				}
				builder.Append(kv.Key);
				builder.Append('=');
				builder.Append(kv.Value);
				index++;
			}
		}
        #endregion
        #region 获取随机数字字符串
        /// <summary>
		/// 定义一个静态的int型变量，保存在服务器内存中，作为Random的种子
		/// </summary>
		public static int staticRndCount = int.MaxValue;
		/// <summary>
		/// 获取随机数字字符串
		/// </summary>
		/// <param name="Length">长度</param>
		/// <returns></returns>
		public static string GetRndNum(int Length) {
			char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
			System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);
			staticRndCount--;
			if (staticRndCount < 0) staticRndCount = int.MaxValue;
			Random rd = new Random(staticRndCount);
			for (int i = 0; i < Length; i++) {
				newRandom.Append(constant[rd.Next(10)]);
			}
			return newRandom.ToString();
		}
		#endregion
        #region 获取时间字符串 格式：yyMMddHHmmssffff
        /// <summary>
        ///  获取时间字符串 格式：yyMMddHHmmssffff
        /// </summary>
        /// <returns></returns>
        public static string GetDatetime() {
            return DateTime.Now.ToString("yyMMddHHmmssffff");
        }
        #endregion
        #region 获取Guid唯一值
        /// <summary>
        /// 获取Guid唯一值
        /// </summary>
        /// <returns></returns>
		public static string GetGuid() {
			return Guid.NewGuid().ToString().Replace("-", "");
		}
        #endregion
        #region 根据日期得到对应的周几
        /// <summary>
        /// 根据日期得到对应的周几
        /// </summary>
        /// <param name="date">日期 如：2016-07-05</param>
        /// <returns></returns>
        public static string GetWeekDayValue(string date) {
            DateTime dt = DataConvert.StrToDateTime(date, DateTime.Now);
            return dt.GetDateTimeFormats('D')[2].Split(',')[0].ToString().Replace("星期", "周");
        }
        #endregion
        #region 判断相关

        /// <summary>
        /// 对象是否等于NULL。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNull(this object value) {
            return value == null;
        }

        /// <summary>
        /// 对象是否不等于NULL。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNotNull(this object value) {
            return value != null;
        }

        /// <summary>
        /// bool类型的值是否为false。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsFalse(this bool value) {
            return value == false;
        }

        /// <summary>
        /// 是否小于等于0。
        /// </summary>
        /// <returns></returns>
        public static bool IsLessOrEqual0(this int value) {
            return value <= 0;
        }

        /// <summary>
        /// 是否不等于0。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNotEqual0(this int value) {
            return value != 0;
        }

        /// <summary>
        /// 判断String是NULL或Empty。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string value) {
            return string.IsNullOrEmpty(value);
        }

        #endregion
	}
}